#!/bin/sh

# shellcheck disable=SC1091
. /usr/libexec/os-helpers-fs

DATA_PARTITION="$(get_state_path_from_label "resin-data")"
LABEL_TIMEOUT=300

# Waiting for the filesystem label
start="$(date +%s)"
end="$start"
while [ ! -L "$DATA_PARTITION" ]; do
	if [ $((end - start)) -le "$LABEL_TIMEOUT" ]; then
		sleep 0.1 && end=$((end + 1))
	else
		echo "[ERROR] Timeout while waiting for filesystem label to appear."
		if [ ! -f /mnt/boot/resin_attempting_fsck_recovery ]; then
			echo "[ERROR] Something bad happened. Assuming storage corruption and attempting fsck and reboot."
			touch /mnt/boot/resin_attempting_fsck_recovery
			fdisk -l | grep '^/dev' | grep -i 'FAT' |  cut -d' ' -f1 | while read line ; do fsck.fat -av $line; done
			fdisk -l | grep '^/dev' | grep -i 'Linux' |  cut -d' ' -f1 | while read line ; do fsck.ext4 -pfv $line; done
			/bin/systemctl --force reboot
		else
			echo "[ERROR] Something bad happened. Failed at recovering via an fsck and reboot cycle"
			exit 0
		fi
	fi
done

# Do nothing if the partition is mounted already
if ! cat /proc/mounts | grep $(readlink -f ${DATA_PARTITION}) > /dev/null; then
	echo "[INFO] Filesystem check on $DATA_PARTITION... "
	e2fsck -y $DATA_PARTITION
	echo "[INFO] Expand ext4 filesystem on $DATA_PARTITION... "
	resize2fs -f $DATA_PARTITION
	sync
fi

if [ -f /mnt/boot/resin_attempting_fsck_recovery ]; then
	echo "[WARN] Looks like there was a successful automated fsck recovery. Please check the integrity of your storage device"
	rm /mnt/boot/resin_attempting_fsck_recovery
fi

exit 0
